package com.shuoyue.ycgk.ui.mine.info;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.shuoyue.ycgk.BuildConfig;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.FileUtil;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.AppVersionInfo;
import com.shuoyue.ycgk.ui.account.UnregistActivity;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.common.download.DownloadContract;
import com.shuoyue.ycgk.ui.main.VersionContract;
import com.shuoyue.ycgk.utils.AppUtil;
import com.shuoyue.ycgk.utils.NOpenFiles;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.NewVersionDialog;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class SettingActivity extends BaseMvpActivity implements DownloadContract.View, VersionContract.View {

    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.version_name)
    TextView versionName;

    DownloadContract.Presenter downloadPresenter;

    VersionContract.Presenter versionPresenter;
    NewVersionDialog newVersionDialog;

    boolean isDownloading = false;
    File apkFile;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView() {
        pageTitle.setText("设置");
        versionName.setText(AppUtil.getVersionName(mContext));
    }

    @Override
    public void initData() {
        downloadPresenter = new DownloadContract.Presenter();
        downloadPresenter.attachView(this);
        versionPresenter = new VersionContract.Presenter();
        versionPresenter.attachView(this);
    }

    @OnClick({R.id.back,
            R.id.lay_password,
            R.id.lay_photo,
            R.id.lay_version,
            R.id.lay_ysxy,
            R.id.lay_yhxy,
            R.id.lay_catch,
            R.id.unregist,
            R.id.lay_about})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lay_password:

                break;
            case R.id.lay_photo:

                break;
            case R.id.lay_version:
                versionPresenter.getVersion();
                break;
            case R.id.lay_catch:
                toast("缓存已清理");
                break;
            case R.id.lay_about:
                CstWebActivity.start(mContext,
                        Constant.ABOUT, "关于我们");
                break;
            case R.id.lay_ysxy:
                CstWebActivity.start(mContext,
                        Constant.YSXY, "隐私条款");
                break;
            case R.id.unregist:
                startActivity(new Intent(mContext, UnregistActivity.class));
                break;
        }

    }


    @Override
    public void downloadSuc(File f) {
        isDownloading = false;

        this.apkFile = f;
        if (newVersionDialog != null && newVersionDialog.isShowing()) {
            newVersionDialog.dismiss();
            newVersionDialog = null;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean haveInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                //权限没有打开则提示用户去手动打开
                setInstallPermission();
            } else {
                NOpenFiles.openFile(this, f);
            }
        } else {
            NOpenFiles.openFile(this, f);

        }
    }

    @Override
    public void progress(int progress) {
        if (newVersionDialog != null) {
            newVersionDialog.changeProgerss(progress);
        }
    }

    @Override
    public void downloadStart() {
        isDownloading = true;
    }

    @Override
    public void downloadError(String msg) {
        isDownloading = false;

    }

    @Override
    public void setAppVersion(AppVersionInfo version) {
        if (version == null) {
            toast("没有查询到最新版本信息");
            return;
        }
        int myVersion = AppUtil.getVersionCode(mContext);
        if (myVersion < version.getVersion()) {
            if (newVersionDialog == null) {
                newVersionDialog = new NewVersionDialog(this);
            }
            newVersionDialog.setDownloadCallback(url -> {
                File dir = new File(FileUtil.getPath(mContext) + "/apk/");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File apkFile = new File(dir.getAbsoluteFile() + "/" + version.getVersion() + ".apk");
                if (apkFile.exists()) {
                    apkFile.delete();
                }
                downloadPresenter.downloadFile(url, apkFile.getAbsolutePath());
            });
            newVersionDialog.show(version);
        } else {
            toast("已经是最新版本");
        }
    }

    @Override
    public void finish() {
        if (isDownloading) {
            HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "提示", "正在下载新版本，是否退出");
            hintConfirmDialog.setOkListener(v -> super.finish());
            hintConfirmDialog.setCancelListener(v -> {
                if (newVersionDialog != null) {
                    newVersionDialog.show();
                }
            });
            hintConfirmDialog.show();
        } else {
            super.finish();
        }

    }


    /**
     * 8.0以上系统设置安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void setInstallPermission() {
        //弹框提示用户手动打开
//        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "权限申请", "是否允许安装位置来源应用？");
//        hintConfirmDialog.setOkListener(v -> {
//            toInstallPermissionSettingIntent();
//            hintConfirmDialog.dismiss();
//
//        });
//        hintConfirmDialog.setCancelListener(v -> {
//            //
//            hintConfirmDialog.dismiss();
//        });
//        hintConfirmDialog.show();
        toInstallPermissionSettingIntent();
    }


    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 1005);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1005) {
//            Toast.makeText(this, "安装应用", Toast.LENGTH_SHORT).show();
            if (apkFile != null) {
                NOpenFiles.openFile(this, apkFile);
            }
        }
    }
}
